$(function () {
	var url = location.search; //获取url中"?"符后的字串
	//当前页面手工测试任务的id
	addManualId = ""; 
	//当前用户名
	userName = "";
    if (url.indexOf("?") != -1) {   
       var str = url.substr(1);   
       path = location.host;
       strs = str.split("&");   
       console.log(strs);
       addManualId = strs[0].split("=")[1];
       userName = strs[1].split("=")[1];
       roleType = Number(strs[2].split('=')[1]);
       platformId = strs[3].split('=')[1];
       platformName = decodeURI((strs[4].split('=')[1]),'UTF-8');
    }  
    //isMainScoket 操作者时为true,访客为false
    //isSimulat 1：手动测试，2：仿真测试
    //roleType 0:仿真测试，1:访客和回放，2:手动测试操作者，3：手动测试回放
    isMainScoket = false;
    isSimulat = 1;
    //当为手动测试和仿真测试时为可以编辑操作,访客和回放不可以操作
    if(roleType == 0 || roleType == 2){
    	isMainScoket = true;
    }else{
    	isMainScoket = false;
    }
    //roleType 0:仿真测试，2:手动测试
    if(roleType == 0 || roleType == 1){
    	isSimulat = 2;
    }else if(roleType == 2 || roleType == 3){
    	isSimulat = 1;
    }
	// 全局变量websocket
	getAllDataWebSocket = "";
	// 拿到手工测试任务ID
	getManualId(); 
	//获取下拉菜单中的参数发送给后台
	getOption(); 
	//默认色灯处于运行状态
	$("#run").css("color", "#61F161"); 
	//默认右侧属性使用复杂模式
	$(".propertySettings").load("../../textcommon/html/simplePropertyTouch.html",null,htmlComplete);
	curruntDeng = "";
	//所有跟踪项
	followItems = [];
	//是否设置跟踪项
	setGGBool = false;
	//是否开始录制
	startLuZhiBool = false;
	//是否开始观测
	startGCBool = false;
	//添加跟踪项数组
	followCheckedArray = [];
	//默认选择端别是I端
	selectXiBieBool = false;
	//默认选择的AB是A
	showImageBool = false;
	dmiDialog = null;
	gGitmes = {};
	//dmi按钮的监听
//	DMIBtnInit();
	//重连时间计时器
	reTimer = null;
	//重连次数
	reConnectCount = 0;
	//是否添加加载动画
	addLoadingBool = true;
	//输入文本框的复杂与简单切换的存储
	completxAndSimpleArray = [];
	//checkbox的复杂与简单切换的存储
	completxAndSimpleChekcArray = [];
	//select的复杂与简单切换的存储
	completxAndSimpleSelectArray = [];
	//色灯的简单与复杂的切换存储
	dengObj = null;
	//右侧属性区域默认为复杂模式complex
	moudle = ""; 
	//请求lkj数据的计时器
	getLKJTimer = null;
	//是否需要请求获取LKJ数据
	getLKJStatuBool = true;
	//发送心跳包计时器
	connectTimer = null;
	//记录输入框1s间隔的计时器
	checkInputTimer = null;
	//请求语音计时器
	getVoiceTimer = null;
	//当前语音的编号
	currentVoiceNum = 0;
	//记录当前音效播放次数
	currentPlayTimes = 0;
	//记录当前音效信息
	currentVoiceData = null;
	//速度相位：
	//当简单模式切换到复杂模式：复杂模式限位都显示简单模式下的速度相位
	//当复杂模式切换到简单模式：复杂模式时第一个切换相位的值就是简单模式下要显示的相位值
	switchSuccesToCompletx = false;
	//监听窗口关闭或页面刷新事件，当窗口关闭或页面刷新时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
	window.onbeforeunload = function () {
		ajaxClose();
	};
	var t = null;
	t = setTimeout(time,1000);//開始运行
	function time()
	{
	   clearTimeout(t);//清除定时器
	   dt = new Date();
	   var year = dt.getFullYear();
	   var month = dt.getMonth() + 1;
	   var day = dt.getDate();
	   var h=dt.getHours();//获取时
	   var m=dt.getMinutes();//获取分
	   var s=dt.getSeconds();//获取秒
	   $("#dateShow").text(year+"-"+month+"-"+day+" "+h+":"+m+":"+s);
	   t = setTimeout(time,1000); //设定定时器，循环运行     
	} 
});

function fullWindowFun(){
//	parent.$(window.parent.document).find("#fullWindow").click();
	var element = document.documentElement;		// 返回 html dom 中的root 节点 <html>
	if(!$('body').hasClass('full-screen')) {
		$('body').addClass('full-screen');
		$('#alarm-fullscreen-toggler').addClass('active');
		// 判断浏览器设备类型
		if(element.requestFullscreen) {
			element.requestFullscreen();
		} else if (element.mozRequestFullScreen){	// 兼容火狐
			element.mozRequestFullScreen();
		} else if(element.webkitRequestFullscreen) {	// 兼容谷歌
			element.webkitRequestFullscreen();
		} else if (element.msRequestFullscreen) {	// 兼容IE
			element.msRequestFullscreen();
		}
		
		$("#fullBtn").html("退出全屏");
	} else {			// 退出全屏
		console.log(document);
		$('body').removeClass('full-screen');
		$('#alarm-fullscreen-toggler').removeClass('active');
		//	退出全屏
		if(document.exitFullscreen) {
			document.exitFullscreen();
		} else if (document.mozCancelFullScreen) {
			document.mozCancelFullScreen();
		} else if (document.webkitCancelFullScreen) {
			document.webkitCancelFullScreen();
		} else if (document.msExitFullscreen) {
			document.msExitFullscreen();
		}
		
		$("#fullBtn").html("全屏显示");
	}
}


function DMIBtnInit(){
	$('#manualtest-disall').click(function () {
		getAllDataWebSocket.send("disAll:true");
		manualtestImageShow();
		console.log("send 四屏显示 disAll:true");
	});
	$('#manualtest-disall').mouseover(function(e){
		$('body').append("<div id='div_toop'>DMI四屏显示</div>");
		$('#div_toop').css({
			'top':"10px",
			'position':'absolute',
			'left':(e.pageX - 135) + "px",
			'background':'#777',
		    'width': '100px',
		    'text-align': 'center',
		    'border-radius': '4px 4px 4px 4px'
		});
	});
	$('#manualtest-disall').mouseout(function(){
		$('#div_toop').remove();
	});
	$('#manualtest-disall').mouseover(function(e){
		$('#div_toop').css({
			'top':"10px",
			'position':'absolute',
			'left':(e.pageX - 135) + "px",
			'background':'#777',
			'width': '100px',
		    'text-align': 'center',
		    'border-radius': '4px 4px 4px 4px'
		});
	});
	
	//ic卡点击
	$('.IcGroove').click(function(){
		BootstrapDialog.show({
		      title: '揭示文件',
		        message: $("<form class='form-inline' style='height:70px'></form>").load('../../textcommon/html/icGroovDetail.html')  ,
		        onshown:function(){
		        	icGrooveData();
		        },
		        buttons : [ {
					icon : 'glyphicon glyphicon-check',
					label : '确定',
					cssClass : 'btn-primary',
					autospin : true,
					action : function(dialogRef) {
						var value = $("#icGrooId").find('option:selected')[0].value;
						if(value == 0){
							var info = "<div style='color:black;'>请选择揭示文件！</div>";
							danger(info);
							return;
						}
						$.ajax({
							type : "POST",
							url : "../../../manualTest/sendICJieShi",
							dataType : "json",
							data : {
								"platformId" : platformId,
								"fileId":value
							},
							success : function(data) {
								if (data.flag == "0") {
									var content = "操作成功!";
									success(content);
								} else {
									var info = "<div style='color:black;'>"+data.errorInfo+"</div>";
									danger(info);
								}
							}
						});
						dialogRef.close();
					}
				}, {
					label : '取消',
					action : function(dialogRef) {
						dialogRef.close();
					}
				} ]
		    });
	});
}
//点击ic卡的界面的数据刷新id填1，揭示文件type=24,车载数据文件type=9,运行组织文件type=10
function icGrooveData(){
	$.ajax({
		url : "../../../LKJSoftwareVersion/getVersionName",
		type : "post",
		data : {
			"sId" : 1,
			"type" : 24
		},
		dataType : "json",
		success:function(data){
			if(data.flag == 0){
				$('#icGrooId').append(new Option("请选择",0));
				for(var i = 0;i<data.content.length;i++){
					$('#icGrooId').append(new Option(data.content[i].VERSION_NAME,data.content[i].VERSION_ID));
				}
			}else{
				danger(data.errorInfo);
			}
		},
		error:function(){
			danger("服务器异常！");
		}
	});
}
// 开始手工测试
function start() {
	var str = addManualId + "," + userName;
	getAllDataWebSocket.send(str);
	return false;
}
//从测试序列界面的链接路径中截取ID
function getManualId() {
	$('#manual-test-platform-name').text(platformName);
	if(roleType == 0 || roleType == 2){//操作者时才初始化平台数据
		addLoading();
		updateTaskPlatform(platformId,addManualId);
	}else{//访客和回放
		MaskIt("#allcontent");
		initWs(path);
	}
}
//请求数据失败后，添加loading
function addLoading(){
	$('body').append("<div class='zezao'></div>");
	$('body').append("<div class='loading loading9'></div>");
	$('.loading9').shCircleLoader({
		color: '#f00'
	});
	$('.loading9').shCircleLoader('progress', '初始化仿真平台中...');
	$('body').css("overflow","hidden");
}

//移除加载动画
function removeLoading(){
	$('.zezao').remove();
	$('.loading9').remove();
	clearTimeout(reTimer);
	$('body').css("overflow","auto");
}


//更新任务和平台的状态
function updateTaskPlatform(platformId,manualId){
	$.ajax({
		"url": "../../../manualTest/updateManualAndPlatformStatus",
		"type": "post",
		"data": {
			"manualId": manualId,
			"manualstatus":1,
			"platformId":platformId,
			"platformStatus":3
		},
		"success": function (result) {
			console.log(result);
			if (result.flag == 0) {
				initASTSData(platformId);
			} else {
				ajaxClose();
				addAlert(result.content);
			}
		},
		"error": function () {
			ajaxClose();
			addAlert("获取仿真测试信息异常！");
		}
	});
}

$("#imageDisplay").click(function () { // 获取图片当前点击位置的坐标
	var x = event.offsetX;
	var y = event.offsetY;
	sendKey(null, 2, 0, x, y); //发送点击的位置坐标给后台
});
// 页面左侧的30个按键的功能函数
function sendKey(th, KeyType, KeyValue, KeyPositionX, KeyPositionY) { // 向后台发送点击坐标位置或者按钮的键值
	var divs = $(".oneButton div"); // 下边的21个按钮
	for (var i = 0; i < divs.length; i++) {
		divs[i].style.border = "1px solid white";
	}
	var btns = $(".menuSettingKey button"); // 右侧的菜单按钮
	for (var j = 0; j < btns.length; j++) {
		btns[j].style.border = "1px solid white";
		$(".warning").css("border", "1px solid white");
	}
	if (th !== null) {
		th.style.border = "1px solid #26C254"; // 点击的按钮边框变色
	}
	console.log(KeyType, KeyValue, KeyPositionX, KeyPositionY);
	var str = "{KeyType:" + KeyType + ",KeyValue:" + KeyValue +
		",KeyPositionX:" + KeyPositionX + ",KeyPositionY:" + KeyPositionY +
		"}";
	if (th !== null) {
		if($(th).attr("id") == "XiBieLight"){
			var duan = "";
			if(!selectXiBieBool){
				duan = 'I 端';
			}else{
				duan = 'II 端';
			}
			ajaxSend(str, 2,$(th).attr("id"),duan);
		}else{
			ajaxSend(str, 2,$(th).attr("id"),"选中");
		}
		
	}else{//点击图片坐标需要特殊处理
		ajaxSend(str, 2,"imageDisplay","("+KeyPositionX+"," +KeyPositionY+")");
	}
}
//按键及信号信息发送ajax
function ajaxSend(str, strName, id, value) {
	$.ajax({
		"url": "../../../manualTest/sendKeyOrSignal",
		"type": "post",
		"data": {
			"type": strName,
			"platformId": platformId,
			"value": str
		},
		"success": function (result) {
			if (result.flag == 0) {
				//操作日志
//				addSimulationManualLog("发送成功！", 1, id, value);
			} else {
				//操作日志
//				addSimulationManualLog(result.errorInfo, 0, id, value);
			}
		},
		"error": function () {
			//操作日志
			addSimulationManualLog("仿真测试连接错误！", 0, event.target.id, event.target.value);
		}
	});
}

function sendTestSignal(destination, signalType, signalValue, id, value) { // 页面右侧的属性值发送后台的功能
	var str = "{destination:" + destination + ",signalType:" + signalType +
		",signalValue:" + signalValue + "}";
	ajaxSend(str, 1, id, value);
}

function onInput(destination, signalType, event) { // input值发生变化时，获取最新的值
	//当文本框输入时，重置计时器
	if(checkInputTimer){
		clearTimeout(checkInputTimer);
	}
	//1s之内没有再输入命令时，发送指令
	checkInputTimer = setTimeout(checkInputFun(destination, signalType, event), 1000);
}

function checkInputFun(destination, signalType, event){
	return function(){
		checkInputShowFun(destination, signalType, event);
	};
}
function checkInputShowFun(destination, signalType, event){
	//当输入框的输入内容不在有效范围内，则提示重新输入
	if (Number(event.value) > Number(event.max) || Number(event.value) < Number(event.min)
			|| event.value=="") {
		event.val(event.min);
		return false;
	}
	var value = event.value;
	event.defaultValue = value;
	sendTestSignal(destination, signalType, value, event.id, event.value);
	//输入框的数据本地存储
	setMANInputLocalStorage(destination, signalType, value);
	
	//记录输入框的数据
	completxAndSimpleFun(signalType,destination,value,event.id);
	
	//复杂模式中，速度改变值，其他的速度也变
	if(event.id == "MANIputStorageId11"){
		$('.departmentSpeed').find('input').val(value);
	}
	
	//速度改变时，仪表盘也转
	if(event.id == "MANIputStorageId402"){
		option.series[0].data[0].value = value;
	    myChart.setOption(option);
	}
	
	//管压
	if(event.id == "MANIputStorageId322"){
		$("#perssureSlider0" ).slider( "value", value );
	}
	
	if(event.id == "MANIputStorageId405"){
		$("#perssureSlider1" ).slider( "value", value );
	}
	
	if(event.id == "MANIputStorageId324"){
		$("#perssureSlider2" ).slider( "value", value );
	}
	
	if(event.id == "MANIputStorageId325"){
		$("#perssureSlider3" ).slider( "value", value );
	}
	
	if(event.id == "MANIputStorageId321"){
		$("#perssureSlider4" ).slider( "value", value );
	}
}

function getOption() { // 获取制式,方向,信号灯内的option内容
	// 每次点击平调运行时，先清空标签
	$(".fxone").empty();
	$(".fxtwo").empty();
	$(".fxthree").empty();
	$(".zsone").empty();
	$(".zstwo").empty();
	$(".zsthree").empty();
	// 加入默认的option
	$(".fxone").append("<option></option>");
	$(".fxtwo").append("<option></option>");
	$(".fxthree").append("<option></option>");
	$(".zsone").append("<option></option>");
	$(".zstwo").append("<option></option>");
	$(".zsthree").append("<option></option>");
	$.ajax({
		"url": "../../../manualTest/getManualTestDicList",
		"type": "post",
		"data": {},
		"success": function (result) {
			var data = result.content;
			if (data[0][0].dictValue == "008") {
				var fx = data[0];
				var fxone = $(".fxone"); // 一系方向
				var fxtwo = $(".fxtwo"); // 二系方向
				for (var i = 0; i < fx.length; i++) {
					fxone.append($("<option signalType='" + 42 +
							"' value="+i+
						" signalValue='" + fx[i].dictdataCode +
						"' destination='" + 1 + "'>" + fx[i].dictdataName +
						"</option>"));
					fxtwo.append($("<option signalType='" + 42 +
							"' value="+i+
						" signalValue='" + fx[i].dictdataCode +
						"' destination='" + 2 + "'>" + fx[i].dictdataName +
						"</option>"));
					$(".fxthree").append($("<option signalType='" + 42 +
							"' value="+i+
							" signalValue='" + fx[i].dictdataCode +
							"' destination='" + 3 + "'>" + fx[i].dictdataName +
							"</option>"));
				}
			}
			if (data[1][0].dictValue == "009") {
				var zs = data[1];
				var zsone = $(".zsone"); // 一系制式
				var zstwo = $(".zstwo"); // 二系制式
				for (var i = 0; i < zs.length; i++) {
					zsone.append($("<option signalType='" + 41 +
							"' value="+i+
						" signalValue='" + zs[i].dictdataCode +
						"' destination='" + 1 + "'>" + zs[i].dictdataName +
						"</option>"));
					zstwo.append($("<option signalType='" + 41 +
							"' value="+i+
						" signalValue='" + zs[i].dictdataCode +
						"' destination='" + 2 + "'>" + zs[i].dictdataName +
						"</option>"));
					$(".zsthree").append($("<option signalType='" + 41 +
							"' value="+i+
							" signalValue='" + zs[i].dictdataCode +
							"' destination='" + 3 + "'>" + zs[i].dictdataName +
							"</option>"));
				}
			}
			if (data[2][0].dictValue == "023") {
				var deng = data[2];
				var dengone = $(".dengone"); // 一系灯
				var dengtwo = $(".dengtwo"); // 二系灯
				for (var i = 0; i < deng.length; i++) {
					dengone.append($("<option signalType='" + 51 +
						"' signalValue='" + deng[i].dictdataCode +
						"' destination='" + 1 + "'>" +
						deng[i].dictdataName + "</option>"));
					dengtwo.append($("<option signalType='" + 51 +
						"' signalValue='" + deng[i].dictdataCode +
						"' destination='" + 2 + "'>" +
						deng[i].dictdataName + "</option>"));
				}
			}
			if (data[3][0].dictValue == "011") { //平调模式色灯展示
				var deng = data[3];
				var dengone = $(".dengone"); // 一系灯
				var dengtwo = $(".dengtwo"); // 二系灯
				if ($(".switchInput").find("#linghtsTwo").length !== 0) {
					$(".dengone").empty();
					$(".dengtwo").empty();
					$(".dengone").append("<option></option>");
					$(".dengtwo").append("<option></option>");
					for (var i = 0; i < deng.length; i++) {
						dengone.append($("<option signalType='" + 52 +
							"' signalValue='" + deng[i].dictdataCode +
							"' destination='" + 1 + "'>" +
							deng[i].dictdataName + "</option>"));
						dengtwo.append($("<option signalType='" + 52 +
							"' signalValue='" + deng[i].dictdataCode +
							"' destination='" + 2 + "'>" +
							deng[i].dictdataName + "</option>"));
					}
				}
				if ($(".buttonLinght").find("#btns").length !== 0) { //简易属性模式内的平调中的30个按钮
					$("#btns").empty();
					for (var i = 0; i < deng.length; i++) {
						$("#btns").append($("<button onclick='btnsparameter(this)' signalType='" + 52 +
							"' signalValue='" + deng[i].dictdataCode +
							"' id='pingdiaoxinhao" + i +
							"' destination='" + 3 + "'>" +
							deng[i].dictdataName + "</button>"));
					}
				}

				//获取本地存储的历史点击按钮，设置按钮状态
				var pingdiaoID = localStorage.getItem('pingdiaoclickstorage');
				$("#btns button").css("border", "1px solid rgb(49, 89, 117)"); //点击的Button边框变色
				$("#btns button").css("background", "#2c3541"); //重置button字颜色为白色
				$('#' + pingdiaoID).css("background", "rgb(40, 107, 187)"); //点击的Button字色
			}
			
			changeComOrSimFun();
		}
	});
}
//下拉框選中變化方法
function optionChange(event) { // 制式，方向，信号灯的三个下拉框选中
	var name = event.className; //下拉框的类名
	if ($(".switchInput").find(".colorLights").length !== 0) { //平调模式不需要变灯的颜色
		var code = $("." + name + " option:selected").attr("signalvalue");
		setLightColor(code, name);
		
		//色灯的简单与复杂的切换存储
		if($("." + name + " option:selected").attr("destination") != 2){
			dengObj = {signalvalue:code,signaltype:$("." + name + " option:selected").attr("signaltype"),
					value:$("." + name + " option:selected").val()};
		}
	}
	if ($("." + name + " option:selected").attr("destination") !== undefined) { // 排除第一个空选项
		var destination = $("." + name + " option:selected").attr("destination");
		var signalType = $("." + name + " option:selected").attr("signalType");
		var signalValue = $("." + name + " option:selected").attr("signalValue");
		sendTestSignal(destination, signalType, signalValue, name, $("." + name + " option:selected").val()); // 数据发送到后台
		completxAndSimpleSelectFun(name,$("." + name + " option:selected")[0].index);
	} else {
		return false;
	}
}
//单选框框選中變化方法
function radioChange(event) { 
	var name = event.className; 
	var destination = $("." + name).attr("destination");
	var signalType = $("." + name).attr("signalType");
	var signalValue = $("." + name).attr("signalValue");
	sendTestSignal(destination, signalType, signalValue, name, "选中"); // 数据发送到后台
}
//根據選中的色燈顯示對應的圖片
//选择灯的类型，改变显示的图片,共三处色灯变化，复杂模式对应一二系色灯，简单模式色灯变化；code代表色灯编码，light；代码哪一处色灯变化
function setLightColor(code, light) {
	var srcpath = "../../images/elements/L.png";
	if (code == 1) {
		srcpath = "../../images/elements/L3.png";
	} else if (code == 2) {
		srcpath = "../../images/elements/L2.png";
	} else if (code == 3) {
		srcpath = "../../images/elements/L.png";
	} else if (code == 4) {
		srcpath = "../../images/elements/LH.png";
	} else if (code == 5) {
		srcpath = "../../images/elements/LH2.png";
	} else if (code == 6) {
		srcpath = "../../images/elements/U.png";
	} else if (code == 7) {
		srcpath = "../../images/elements/U2S.gif";
	} else if (code == 8) {
		srcpath = "../../images/elements/U2.png";
	} else if (code == 9) {
		srcpath = "../../images/elements/U3.png";
	} else if (code == 10) {
		srcpath = "../../images/elements/UUS.gif";
	} else if (code == 11) {
		srcpath = "../../images/elements/UU.png";
	} else if (code == 12) {
		srcpath = "../../images/elements/HUS.gif";
	} else if (code == 13) {
		srcpath = "../../images/elements/HU.png";
	} else if (code == 14) {
		srcpath = "../../images/elements/HY.png";
	} else if (code == 15) {
		srcpath = "../../images/elements/L4.png";
	} else if (code == 16) {
		srcpath = "../../images/elements/L5.png";
	} else if (code == 17) {
		srcpath = "../../images/elements/WZ.png";
	} //
	else if (code == 18) {
		srcpath = "../../images/elements/27.9.png";
	} else if (code == 19) {
		srcpath = "../../images/elements/H.png";
	} else if (code == 20) {
		srcpath = "../../images/elements/B.png";
	}
	var img = $("<img src='' alt=''>");
	if (light == "dengone") {
		$(".semaphoresOne").empty();
		$(".semaphoresOne").append(img);
		$(".semaphoresOne img").attr("src", srcpath);
	} else if (light == "dengtwo") {
		$(".semaphoresTwo").empty();
		$(".semaphoresTwo").append(img);
		$(".semaphoresTwo img").attr("src", srcpath);
	} else if (light == "dengs") {
		$(".dengs").empty();
		$(".dengs").append(img);
		$(".dengs img").attr("src", srcpath);
	}

}
/**
 * 发送复选框信息
 * @param {} current 
 */
function getCheckbox(current) { // 获取复选框的键值对发送到后台
	var name = current.className;
	var mode=$(".menuImage").attr("data");
	var destination = current.getAttribute("destination");
	var signalType = current.getAttribute("signalType");
	if(mode=="simple"){
		//如果是简单页面,选中则发110,否则0
		if (current.checked == true) { // 如果是选中状态
			sendTestSignal(destination, signalType, 110, name, "选中"); // 数据发送到后台
		} else {
			sendTestSignal(destination, signalType, 0, name, "未选中"); // 数据发送到后台
		}
	}else if(mode=="complex"){
		//如果是复杂页面,那么选中则发送input中的值,位选中则发0
		if (current.checked == true) { // 如果是选中状态
			var voltage=$('#MANIputStorageId404').val();
			sendTestSignal(destination, signalType, voltage, name, "选中"); // 数据发送到后台
		} else {
			sendTestSignal(destination, signalType, 0, name, "未选中"); // 数据发送到后台
		}
	}
	
	completxAndSimpleCheckBoxFun(signalType,destination,current.checked);
}

function getRadio(destination, signalType, signalValue, classString1, classString2) { // 获取单选框的键值对发送到后台
	if (classString2) {
		sendTestSignal(destination, signalType, signalValue, classString1, "选中");
	} else {
		sendTestSignal(destination, signalType, signalValue, classString1, guojiFun(destination, signalType));
	}

	//把操作存储到本地，classString1，classString2，为对应操作的class
	setMANRadioLocalStorage(classString1, classString2);
}

function switchLinght() { //点击运行，平调区域，切换色灯的显示方法
	//为了实现从BTM切换时，默认为简单模式
	$(".menuImage").attr("data", "simple");
	getLKJStatuBool = false;//此时不需要LKJ获取数据计时器
	$("#runningFlat").css("border", "1px solid green");
	$("#runningFlat").css("background", "#556B2F"); //点击的圆形变色
	//复杂属性的平调运行切换效果
	if ($(".switchInput").find(".colorLights").length !== 0) {
		$(".switchInput").empty(); //清空色灯区域，放入下拉框
		$("#run").css("color", "white");
		$("#flat").css("color", "#61F161"); //显示平调的灯
		$(".switchInput").load("../../textcommon/html/manualTestPageLinghtTwo.html");
		getOption(); //重新加载灯内的选项参数 

	} else if ($(".switchInput").find("#linghtsTwo").length !== 0) {
		$(".switchInput").empty(); //清空色灯区域，放入下拉框
		$("#run").css("color", "#61F161");
		$("#flat").css("color", "white"); //显示运行的灯
		$(".switchInput").load("../../textcommon/html/manualTestPageLinghtOne.html");
		getOption(); //重新加载灯内的选项参数
	}
	//简单属性模式的平调和运行切换效果
	// 如果是色灯按钮样式
	else if ($(".buttonLinght").find("#btns").length !== 0) { //色灯信号 
		$(".buttonLinght").empty();
		$("#run").css("color", "#61F161");
		$("#flat").css("color", "white"); //显示运行的灯
		$(".buttonLinght").load("../../textcommon/html/easyMoudleLinghtOneTouch.html");
		$("#sedengs .condition #radio").css("margin-bottom", "74px");
		return false;
	} else if ($(".buttonLinght").find(".leftLinght").length !== 0) { //平调信号
		$(".buttonLinght").empty();
		$("#run").css("color", "white");
		$("#flat").css("color", "#61F161"); //显示运行的灯
		$(".buttonLinght").append("<div id='btns'></div>");
		$("#sedengs .condition #radio").css("margin-bottom", "96px");
		getOption(); //重新加载灯内的选项参数
	}

}

function moudleSwitch() { //点击浏览器图标，切换右侧属性区域的复杂和简单模式
	moudle = $(".menuImage").attr("data"); // 右侧属性区域默认为复杂模式complex
	//切换前的处理
	preDeel();
	if (moudle == "complex") { //右侧属性切换为复杂模式
		switchSuccesToCompletx = true;
		if ($(".propertySettings").find(".signalings").length !== 0 || $(".propertySettings").find("styele").length == 0) {
			$(".propertySettings").empty(); //清空右侧属性值区域
			$(".propertySettings").load("../../textcommon/html/complexPropertiesTouch.html",null,htmlComplete);
			$(".menuImage").attr("data", "simple");
			getOption(); //重新加载灯内的选项参数
			$(".buttonLinght").load("../../textcommon/html/easyMoudleLinghtOne.html");
		}
		getLKJStatuBool = false;//此时不需要LKJ获取数据计时器
		return false;
	} else if (moudle == "simple") { //右侧属性切换为简单模式
		getLKJStatuBool = true;//此时需要LKJ获取数据计时器
		if ($(".propertySettings").find("#leftOne").length !== 0 || $(".propertySettings").find("styele").length == 0) {
			$(".propertySettings").empty(); //清空右侧属性值区域
			$(".propertySettings").load("../../textcommon/html/simplePropertyTouch.html",null,htmlComplete);
			$(".menuImage").attr("data", "complex");
			getOption(); //重新加载灯内的选项参数
		}
	}
}
// 简单属性模式内的平调模式中的30个按钮点击传递参数
function btnsparameter(th) {
	$("#btns button").css("background", "#2c3541"); //重置button字颜色为白色
	$(th).css("background", "rgb(40, 107, 187)"); //点击的Button字色
	var signalValue = ($(th).attr("signalValue"));
	var signalType = ($(th).attr("signalType"));
	var destination = ($(th).attr("destination"));
	sendTestSignal(destination, signalType, signalValue, ($(th).attr("id")), "选中 " + $(th).html()); //发送到后台

	//存储点击的第一个按钮到本地
	localStorage.setItem('pingdiaoclickstorage', ($(th).attr("id")));
}
// 简单属性模式下点击按钮更换色灯图片并同时发送1,2系参数
function linghts(th, destination, signalType, signalValue) {
	var data = $(th).attr("data");
	var bool = true; //色灯是否亮起
	if (curruntDeng != signalValue) {
		$(".rightButton button").css("background", "#2c3541"); //重置button字颜色为白色
		$(th).css("background", "rgb(40, 107, 187)"); //点击的Button字色
		sendTestSignal(destination, signalType, signalValue, $(th).attr("class"), "打开 " + $(th).html()); //发送到后台
		setLightColor(signalValue, "dengs"); //色灯变色
		$(th).attr("data", "2");
		bool = true;
	} else {
		if (data == "1") { //按钮的色灯状态
			$(".rightButton button").css("background", "#2c3541"); //重置button字颜色为白色
			$(th).css("background", "rgb(40, 107, 187)"); //点击的Button字色
			sendTestSignal(destination, signalType, signalValue, $(th).attr("class"), "打开 " + $(th).html()); //发送到后台
			setLightColor(signalValue, "dengs"); //色灯变色
			$(th).attr("data", "2");
			bool = true;
		} else if (data == "2") { //按钮的灭灯状态
			$(".rightButton button").css("background", "#2c3541"); //重置button字颜色为白色
			$(th).css("background", "#2c3541"); //点击的Button边框变色
			sendTestSignal(3, 51, 17, $(th).attr("class"), "关闭 " + $(th).html()); //发送灭灯的键值到后台
			setLightColor(17, "dengs"); //色灯变色
			$(th).attr("data", "1");
			bool = false;
		}
	}
	
	//简单与复杂的切换存储
	if(bool){
		dengObj = {signalvalue:signalValue,signaltype:signalType};
	}else{
		dengObj = null;
	}
	curruntDeng = signalValue;

	//存储被点击的按钮id
	localStorage.setItem('RightButtonStorage', signalValue + "?" + bool);
}

//进行预处理，比如停止循环获取状态信息。
function preDeel() {
	if (window.systemStateHandle != null) {
		clearInterval(window.systemStateHandle);
	}
}
// 右侧的六个圆形设置按钮，点击更换设置界面的效果
function menuAims(moudel, th) {
	//为了实现从BTM切换时，默认为简单模式
	$(".menuImage").attr("data", "simple");
	getLKJStatuBool = false;//此时不需要LKJ获取数据计时器
	$(".nav div").css("border", "none"); //清除所有的圆形的颜色
	$(".nav div").css("background", "#313873"); //清除所有的圆形的颜色
	$(th).css("border", "1px solid green"); //点击的圆形变色
	$(th).css("background", "#556B2F"); //点击的圆形变色
	//预处理
	preDeel();
	if (moudel == "ATP") {
		$(".propertySettings").empty(); //清空右侧属性值区域
		$(".propertySettings").load("../../textcommon/html/atpTouch.html?addManualId=" + addManualId);
	} else if (moudel == "EMU") {
		$(".propertySettings").empty(); //清空右侧属性值区域
		$(".propertySettings").load("../../textcommon/html/emuTouch.html?addManualId=" + addManualId);
	} else if (moudel == "BTM") {
		$(".propertySettings").empty(); //清空右侧属性值区域
		$(".propertySettings").load("../../textcommon/html/btmTouch.html?addManualId=" + addManualId);
	} else if (moudel == "TCR") {
		$(".propertySettings").empty(); //清空右侧属性值区域
		$(".propertySettings").load("../../textcommon/html/tcrTouch.html?addManualId=" + addManualId);
	} else if (moudel == "TAX") {
		$(".propertySettings").empty(); //清空右侧属性值区域
		$(".propertySettings").load("../../textcommon/html/taxTouch.html?addManualId=" + addManualId);
	} else if (moudel == "LAIS") {
		$(".propertySettings").empty(); //清空右侧属性值区域
		$(".propertySettings").load("../../textcommon/html/laisTouch.html?addManualId=" + addManualId);
	} else if (moudel == "STA") {
		$(".propertySettings").empty(); //清空右侧属性值区域
		$(".propertySettings").load("../../textcommon/html/staTouch.html?addManualId=" + addManualId);
	}
}
// 初始化websocket
function initWs(ip) {
	var connectIp = 'ws://' + ip + '/asts/manual/testWebsocket/{'+addManualId+'}/{'+userName+'}/{'+isMainScoket+'}/{'+isSimulat+'}';
	console.log(connectIp);
	getAllDataWebSocket = new WebSocket(connectIp);
	getAllDataWebSocket.onmessage = function (event) {
		getAllDataWebSocketMessage(event);
	};

	getAllDataWebSocket.onerror = function (event) {
		getAllDataWebSocketError(event);
	};
	getAllDataWebSocket.onopen = function (event) {
		getAllDataWebSocketOpen(event);
	};
	getAllDataWebSocket.onclose = function (event) {
		getAllDataWebSocketClose(event);
	};
	//监听窗口关闭或页面刷新事件，当窗口关闭或页面刷新时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
	window.onbeforeunload = function () {
		ajaxClose();
	};
}
var textImage = "";
var idImage="";
// 从后台获取到所有的需要的数据，包括图片，日志信息，进度，数据。
function getAllDataWebSocketMessage(event) {
	var pojo = event.data;
	var gettype = Object.prototype.toString;
	if (gettype.call(pojo) == "[object Blob]") {//返回图片信息
		if(idImage!=""){
			loadPicture(pojo,idImage,textImage);
		}
	}else if(gettype.call(pojo) == "[object String]" && pojo.split("broadcast:")[1]){//仿真测试访客日志信息
		addManualLogNew(pojo.split("broadcast:")[1]);
	}else if(gettype.call(pojo) == "[object String]" && pojo.indexOf("testExit")>=0){//完成后测试后退出
		addAlert("测试已完成，请退出！");
		//提示操作者退出时，访客断开websocket连接
		if(getAllDataWebSocket){
			getAllDataWebSocket.close();
		}
	}else{
		var obj = eval('(' + pojo + ')');
		if(obj.operateLog){////手动测试回放日志信息
			addManualLogNew(obj.operateLog);
		}else if(obj.code>=0){//收到语音信息
			var code = obj.code;
			var time = obj.time;
			playVoice(code,time);
		}else{//图像位置信息
			var flag = obj.flag;
			if (flag == 0) { 
				textImage = obj.textImage;
				idImage = obj.id;
			} else {
				var info = obj.info;
				var content = "<span style='color:black;'>" + info + "</span>";
				BootstrapDialog.show({
					title: '提示',
					message: content,
					buttons: [{
						icon: 'glyphicon glyphicon-check',
						label: '确定',
						cssClass: 'btn-primary',
						autospin: true,
						action: function () {
							window.location.href = "../../test/html/manualTestMain.html?userName=" + userName;
						}
					}]
				});
			}
		}
	}
}

function getAllDataWebSocketOpen(event) {
	start(); // 开始手工测试
}

function getAllDataWebSocketError(event) {
	console.log(event.data);
}

function getAllDataWebSocketClose(event) {
	getAllDataWebSocket.close();
}

//释放平台
function ajaxClose() {
	 if(roleType == 1){//当为访客时，不需要释放平台
		 return;
	 }
	 console.log("断开websocket");
	 $.ajax({
		"url": "../../../manualTest/stopManualTest",
		"type": "post",
		"data": {
			"manualId": addManualId,
			 platformId:platformId
		}
	});
}
//获取语音
function playVoice(code, time) {
	if (code) {// 判断返回音效代码是否为空
		var music = $('#bgMusic')[0];
		if (parseInt(code) > 0 && parseInt(time) > 0) {// 开始播放音频
			// console.log("成功：：：：：："+code+"||||"+time);
			// 不重复播放同一个语音
			if (currentVoiceNum != parseInt(code)) {
				// 重置音效播放的次数
				currentPlayTimes = 0;
				// 重置获取到当前音效的信息
				currentVoiceData = {code:code,time:time};
				// 开始播放音效，播放次数为一次的语音之间间隔一秒
				if (time == 1 && currentVoiceNumCopy == parseInt(code)) {
					setTimeout(playVoiceFun, 1000);
				} else {
					playVoiceFun();
				}
				// 记录当前播放音效的code，为了不重复播放用一个音效
				currentVoiceNum = parseInt(code);
				currentVoiceNumCopy = parseInt(code);
			}
		} else {
			// console.log("为0语音"+code+"||||"+time);
			if (!music.paused) {
				music.pause();
				$("#audioBtn").removeClass("play").addClass("pause");
			}
		}
	}
}

// 播放音效
function playVoiceFun(){
	// console.log('开始播放音效');
	var music=$('#bgMusic')[0];
	//音效播放次数加1
	currentPlayTimes++;
	$('#bgMusic').attr('src',"../../textcommon/voice/"+parseInt(currentVoiceData.code)+".mp3");
	music.play();
	$("#audioBtn").removeClass("pause").addClass("play");
}

//监听语音播放完成
function playOver(){
	//console.log("音效播放第"+currentPlayTimes+"次完成");
	//如果播放次数小于当前音效需要的播放的次数，那么再播放一次当前音效
	if(currentPlayTimes<parseInt(currentVoiceData.time)){
		playVoiceFun();
	}else{
		//当前语音播放次数完成后，重置记录的语音code
		if(currentVoiceData.time == 1){
			currentVoiceNum = 0;
		}
	}
}

// 加载图片
function loadPicture(pic, id, imageText) {
	// 创建FileReader对象，该对象时html5中的特有对象，详细用法可以//参照html5相关资料
	var reader = new FileReader();
	// 设置FileReader对象的读取文件回调方法
	reader.onload = function (eve) {
		// 判断文件是否读取完成
		if (eve.target.readyState == FileReader.DONE) {
			if (showImageBool) {
				//如果显示着外部屏幕
				// 读取文件完成后，创建img标签来显示服务端传来的字节数//组
				$('#'+id).find('img').attr('src',this.result);
				$('#'+id).find('div').html(imageText);
			} else {
				//如果显示着外部屏幕
				// 读取文件完成后，创建img标签来显示服务端传来的字节数//组
				// 读取文件完成后内容放在this===当前
				// fileReader对象的result属性中，将该内容赋值img标签//浏览器就可以自动解析内容格式并且渲染在浏览器中
				$('#'+id).find('img').attr('src',this.result);
			}
		}
	};
	// 调用FileReader的readAsDataURL的方法自动就会触发onload事件
	reader.readAsDataURL(pic);
};

//显示四屏
function manualtestImageShow() {
	dmiDialog = BootstrapDialog.show({
		closable:function(){
			$(this).on('click',function(){
				showImageBool = false;
				setDisAll();
			});
		},
		title: 'DMI四屏显示',
		message: $("<form class='form-inline' style='height:600px;width:1330px'></form>").load('../../textcommon/html/manualCellView.html'),
		onshown: function() {
			showImageBool = true;
		},
		buttons: [{
			icon: 'glyphicon glyphicon-check',
			label: '确定',
			cssClass: 'btn-primary',
			autospin: true,
			action: function(dialogRef) {
				showImageBool = false;
				setDisAll();
				dialogRef.close();
			}
		}]
	});
}

function setDisAll(){
	getAllDataWebSocket.send("disAll:false");
	console.log("send 四屏显示 disAll:false");
}

//输入框的数据本地存储
function setMANInputLocalStorage(destination, signalType, value) {
	localStorage.setItem('MANIputStorage' + destination + signalType, value);
}
//读取本地操作的数据
function setMANRadioLocalStorage(classString1, classString2) {
	localStorage.setItem(classString1, true);
	localStorage.setItem(classString2, false);
}

//设置跟踪项按点击
function setFollow(){
	$.ajax({
		type: "POST",
		url: "../../../manualTest/getMonitorItems",
		success: function(data) {
			followItems = data.content;
			BootstrapDialog.show({
				title: '设定跟踪项',
				message: $("<form class='form-inline' style='height:400px;width:735px;overflow: auto;'></form>").load('../../textcommon/html/following.html'),
				onshown: function() {
					updataFollowData();
				},
				buttons: [{
					icon: 'glyphicon glyphicon-check',
					label: '确定',
					cssClass: 'btn-primary',
					autospin: true,
					action: function(dialogRef) {
						sendFollowData();//发送设定跟踪项请求
					}
				}, {
					label: '取消',
					action: function(dialogRef) {
						dialogRef.close();
					}
				}]
			});
		},
		error: function(err) {
			danger("服务器异常!");
		}
	});
}
//发送设定跟踪项请求
function sendFollowData(){
	gGitmes = getItemsData();
	//跟踪项添加成功
	setGGBool = true;
	updateLZButtonState();
	content = "<div style='color:black;'>设置跟踪项成功！</div>";
	success(content);
}

//设置跟踪项的数据
function updataFollowData(){
	followCheckedArray = [];
	var htmlData="";
	for(var i = 0;i<followItems.length;i++){
		htmlData = htmlData + "<div class='followCell'><input type='checkbox'signalType="+
		followItems[i].CODE+" id='followCheckbox_"+
		i+"'><div class='followLabel'>"+
		followItems[i].NAME+"</div><div class='followSelect'><select class='followSelectDetail' id='followSelect_"+
		i+"'><option>两系同时</option><option destination='1'>Ⅰ系</option><option destination='2'>Ⅱ系</option></select></div></div>";
	}
	
	$('.followDiv').html(htmlData);
}

//获取设置的跟踪项数据
function getItemsData(){
	var str = "{";
	var destination=0;
	var signalType = 0;
	for(var i = 0;i<followItems.length;i++){
		if($('#followCheckbox_'+i).is(':checked')){
			signalType = $("#followCheckbox_" + i).attr("signalType");
			if ($("#followSelect_" + i + " option:selected").attr("destination") !== undefined) { // 排除第一个空选项
				destination = $("#followSelect_" + i + " option:selected").attr("destination");
				str = str+destination+":"+signalType+",";
			} else {
				str = str+"3"+":"+signalType+",";
			}
		}
	}
	str = str.substring(0, str.length - 1);
	str = str+"}";
	return str;
}

//切换系别
function changeXiBie(th){
	selectXiBieBool = !selectXiBieBool;
	if(!selectXiBieBool){
		$('.duan').html('I 端');
	}else{
		$('.duan').html('II 端');
	}
	var value= 5;
	if(!selectXiBieBool){
		value = 5;
	}else{
		value = 6;
	}
	sendKey(th, 3, value, 0, 0); //发送点击的位置坐标给后台
}
//点击A机B机
function clickAB(type,th){
	var value= 9;
	if(type == 0){
		value = 9;
		$('#AC').addClass('activeAB');
		$('#BC').removeClass('activeAB');
		$('#ALight').css('background','#00FF01');
		$('#BLight').css('background','#292929');
	}else{
		value = 10;
		$('#BC').addClass('activeAB');
		$('#AC').removeClass('activeAB');
		$('#ALight').css('background','#292929');
		$('#BLight').css('background','#00FF01');
	}
	sendKey(th, 3, value, 0, 0); //发送点击的位置坐标给后台
}
//LKJ输出状态刷新
function udpateLKJStatu(){
	if(!getLKJStatuBool){//此时不行要请求LKJ数据
		return;
	}
	$.ajax({
		type : "POST",
		url : "../../../manualTest/getLKJOutPutInfo",
		dataType : "json",
		data : {
			"platformId" : platformId
		},
		success : function(data) {
			if (data.flag == "0") {
				//console.log(data);
				var statuArray = [data.content.xieZai,data.content.jianYa,
				                  data.content.guanFeng,data.content.jinJi1,
				                  data.content.jinJi2,data.content.beiYong1,
				                  data.content.beiYong2,data.content.beiYong3,
				                  data.content.beiYong4,data.content.beiYong5];
				for(var i = 0;i<statuArray.length;i++){
					if(statuArray[i] == 0){
						$("#LKJStatuLeft"+i).css("background", "gray");
						if($("#LKJStatuRight"+i)){
							$("#LKJStatuRight"+i).css("background", "gray");
						}
					}else if(statuArray[i] == 1){
						$("#LKJStatuLeft"+i).css("background", "red");
						if($("#LKJStatuRight"+i)){
							$("#LKJStatuRight"+i).css("background", "gray");
						}
					}else if(statuArray[i] == 2){
						$("#LKJStatuLeft"+i).css("background", "gray");
						if($("#LKJStatuRight"+i)){
							$("#LKJStatuRight"+i).css("background", "green");
						}
					}else{
						$("#LKJStatuLeft"+i).css("background", "red");
						if($("#LKJStatuRight"+i)){
							$("#LKJStatuRight"+i).css("background", "green");
						}
					}
				}
				
				$('#MANIputStorageId400').val(data.content.szbShiSu);
				$('#MANIputStorageId401').val(data.content.szbXianSu);
			} else {
				var info = "<div style='color:black;'>"+data.errorInfo+"</div>";
				danger(info);
			}
			
			getLKJTimer = setTimeout('udpateLKJStatu()', 1000);
		}
	});
}
//初始化仿真平台状态
function initASTSData(platformId)
{   
	console.log("开始初始化平台");
	$.ajax({
		type : "POST",
		url : "../../../manualTest/initASTSDevice",
		dataType : "json",
		data : {
			"platformId" : platformId
		},
		success : function(data) {
			if (data.flag == "0") {
				removeLoading();
				console.log("初始化平台完成");
				initWs(path);
				initSendAjaxSend();
			} else {
				ajaxClose();
				addAlert(data.errorInfo);
			}
		},
		error:function(data){
			ajaxClose();
			addAlert(data.errorInfo);
		}
	});
}

//首次进入界面，发送不为零的参数
function initSendAjaxSend() {
	var inputArray = $('.signalings').find('input');
	for(var i = 0;i<inputArray.length;i++){
		if(inputArray[i].value !='0' && inputArray[i].value !=""){
			var strInput = inputArray[i].oninput+"";
			var msgArray = strInput.split('{')[1].split('}')[0].split("(")[1].split(")")[0].split(',');
			var str = "{destination:" + msgArray[0] + ",signalType:" + msgArray[1] +
			",signalValue:" + inputArray[i].value + "}";
			initSendData(str,1);
		}
	}
}
//首次进入界面，发送不为零的参数请求的接口
function initSendData(str, strName){
	$.ajax({
		"url": "../../../manualTest/sendKeyOrSignal",
		"type": "post",
		"data": {
			"type": strName,
			"platformId": platformId,
			"value": str
		},
		"success": function (result) {
			if (result.flag == 0) {
				
			}
		},
		"error": function () {
			
		}
	});
}

//简单和复杂来回切换时，数据的对应关系，
//1、简单到复杂：简单的数据赋值给复杂的I 和II 系
//2、复杂到简单：复杂的I系数据赋值给简单的数据
function completxAndSimpleFun(signaltype,destination,value,id)
{
	if(destination == 2 || (signaltype>=11 && signaltype<=14)){//II系的数据不用记录
		if(signaltype == 1){
			
		}
		return;
	}
	var isBool = false;//判断当前是否已经存储当前的属性对应的数据
	var index = 0;
	for(var i = 0;i<completxAndSimpleArray.length;i++){
		if(signaltype == completxAndSimpleArray[i].signaltype){
			isBool = true;
			index = i;
			break;
		}
	}
	if(signaltype != 1){
		if(!isBool){
			completxAndSimpleArray.push({signaltype:signaltype,value:value});
		}else{
			completxAndSimpleArray[index].value = value;
		}
	}else{//速度的复杂与简单的切换
		if(id == "MANIputStorageId402" || id == "MANIputStorageId11"){//简单界面的记录
			if(!isBool){
				completxAndSimpleArray.push({signaltype:"1",value:value});
			}else{
				completxAndSimpleArray[index].value = value;
			}
		}
	}
}

//切换到复杂界面的时候的数据处理
function htmlComplete(){
	udpateLKJStatu();//更新显示LKJ状态
	if($(".menuImage").attr("data") == "complex"){
		//速度的仪表盘
		addSpeedEchart();
		//添加管压
		addPressure();
		//添加相位
		addXW();
		//速度相位的默认值
		var xwLocalStorage = localStorage.getItem("xwSlider");
		if(xwLocalStorage){
			$("xwSlider").slider("value",xwLocalStorage);
		}
	}else{
		//速度相位的默认值
		var xwLocalStorage = Number(localStorage.getItem("xwSlider"))+1;
		if(xwLocalStorage){
			$(".departmentSpeed").find("select").each(function(index,e){
				$(e).find("option:eq("+xwLocalStorage+")").attr("selected","selected");
			});
		}
	}
	//添加数字软键盘
	addNumberKeyboard();
	
	var inputArray = $('.propertySettings').find('input');
	for(var j = 0;j<completxAndSimpleArray.length;j++){
		for(var i = 0;i<inputArray.length;i++){
			if(inputArray[i].oninput){
				var strInput = inputArray[i].oninput+"";
				var msgArray = strInput.split('{')[1].split('}')[0].split("(")[1].split(")")[0].split(',');
				var signaltype = msgArray[1];
				if(signaltype == 32 || signaltype == 2){//双针表速度和电流没有对应的复杂和简单切换
					continue;
				}
				if(completxAndSimpleArray[j].signaltype == signaltype){
					$('#'+inputArray[i].id).val(completxAndSimpleArray[j].value);
					//当简单模式下的速度时，仪表盘也更新数据
					if(inputArray[i].id == "MANIputStorageId402"){
						// 使用刚指定的配置项和数据显示图表。
					    option.series[0].data[0].value = completxAndSimpleArray[j].value;
						myChart.setOption(option);
					}
					//管压
					//管压
					if(inputArray[i].id == "MANIputStorageId322"){
						$("#perssureSlider0" ).slider( "value", completxAndSimpleArray[j].value );
					}
					
					if(inputArray[i].id == "MANIputStorageId405"){
						$("#perssureSlider1" ).slider( "value", completxAndSimpleArray[j].value );
					}
					
					if(inputArray[i].id == "MANIputStorageId324"){
						$("#perssureSlider2" ).slider( "value", completxAndSimpleArray[j].value );
					}
					
					if(inputArray[i].id == "MANIputStorageId325"){
						$("#perssureSlider3" ).slider( "value", completxAndSimpleArray[j].value );
					}
					
					if(inputArray[i].id == "MANIputStorageId321"){
						$("#perssureSlider4" ).slider( "value", completxAndSimpleArray[j].value );
					}
					
					if(signaltype == 1){//速度的值和其他8个的速度值同时变化
						$('.departmentSpeed').find('input').val(completxAndSimpleArray[j].value);
					}
				}
			}
		}
	}
	var checkboxArray = $('.propertySettings').find('input');
	for(var p = 0;p<completxAndSimpleChekcArray.length;p++){
		for(var q = 0;q<checkboxArray.length;q++){
			if(checkboxArray[q].type =="checkbox"){
				if(completxAndSimpleChekcArray[p].signalType == checkboxArray[q].getAttribute("signaltype")){
					$('.'+checkboxArray[q].getAttribute("class")).attr('checked',completxAndSimpleChekcArray[p].checked);
				}
			}
		}
	}
}
//多选框的复杂和简单的切换的逻辑的处理
function completxAndSimpleCheckBoxFun(signalType,destination,checkBool){
	if(destination == 2){
		return;
	}
	var bool = false;
	var index = 0;
	for(var i = 0;i<completxAndSimpleChekcArray.length;i++){
		if(completxAndSimpleChekcArray[i].signalType == signalType){
			bool = true;
			index = i;
			break;
		}
	}
	
	if(bool){
		completxAndSimpleChekcArray[index].checked = checkBool;
	}else{
		completxAndSimpleChekcArray.push({signalType:signalType,checked:checkBool});
	}
}

//select的复杂到简单的存储
function completxAndSimpleSelectFun(name,value){
	if(name == "zstwo" || name == "fxtwo"){
		return;
	}
	var valueName  ="";
	if(name == "zsone" || name == "zsthree"){
		valueName = "ZS";
	}else{
		valueName = "FX";
	}
	var bool = false;
	var index = 0;
	for(var i = 0;i<completxAndSimpleSelectArray.length;i++){
		if(completxAndSimpleSelectArray[i].valueName == valueName){
			bool = true;
			index = i;
			break;
		}
	}
	
	if(bool){
		completxAndSimpleSelectArray[index].value = value;
	}else{
		completxAndSimpleSelectArray.push({valueName:valueName,value:value});
	}
	
	//速度相位
	if(name.indexOf("suduSelect")>=0&& switchSuccesToCompletx){
		switchSuccesToCompletx = false;
		if(value == 1){
			localStorage.setItem("xwSlider", 0);
		}else if(value == 2){
			localStorage.setItem("xwSlider", 1);
		}
	}
}

//select的简单与复杂的切换
function changeComOrSimFun(){
	for(var m = 0;m<completxAndSimpleSelectArray.length;m++){
		if(completxAndSimpleSelectArray[m].valueName == "ZS"){
			if($('.zsone')){
				$(".zsone option:eq("+Number(completxAndSimpleSelectArray[m].value)+")").prop('selected',true);
			}
			if($('.zstwo')){
				$(".zstwo option:eq("+Number(completxAndSimpleSelectArray[m].value)+")").prop('selected',true);
			}
			if($('.zsthree')){
				$(".zsthree option:eq("+Number(completxAndSimpleSelectArray[m].value)+")").prop('selected',true);
			}
		}else{
			if($('.fxone')){
				$(".fxone option:eq("+Number(completxAndSimpleSelectArray[m].value)+")").prop('selected',true);
			}
			if($('.fxtwo')){
				$(".fxtwo option:eq("+Number(completxAndSimpleSelectArray[m].value)+")").prop('selected',true);
			}
			if($('.fxthree')){
				$(".fxthree option:eq("+Number(completxAndSimpleSelectArray[m].value)+")").prop('selected',true);
			}
		}
	}
	if(dengObj){
		$(".dengone").children("option").each(function() {
			var temp_value = $(this).attr('signalvalue');
			if (temp_value == dengObj.signalvalue) {
				$(this).attr("selected", "selected");
				setLightColor(dengObj.signalvalue, "dengone");
			}
		});
		$(".dengtwo").children("option").each(function() {
			var temp_value = $(this).attr('signalvalue');
			if (temp_value == dengObj.signalvalue) {
				$(this).attr("selected", "selected");
				setLightColor(dengObj.signalvalue, "dengtwo");
			}
		});
		
		var buttonArray = $('.rightButton').find('button');
		for(var i =0;i<buttonArray.length;i++){
			var str = buttonArray[i].getAttribute('onclick')+"";
			var buttonSignalValue = str.split('(')[1].split(')')[0].split(',')[3];
			if(buttonSignalValue == dengObj.signalvalue){
				$(".rightButton button").css("border", "1px solid rgb(49, 89, 117)");
				$(".rightButton button").css("background", "#2c3541"); //重置button字颜色为白色
				$('.'+buttonArray[i].getAttribute('class')).css("border", "rgb(40, 107, 187)"); //点击的Button边框变色
				$('.'+buttonArray[i].getAttribute('class')).css("background", "rgb(40, 107, 187)"); //点击的Button字色
				setLightColor(dengObj.signalvalue, "dengs"); //色灯变色
				$('.'+buttonArray[i].getAttribute('class')).attr("data", "2");
				break;
			}
		}
	}
}

function MaskIt(obj){
    var hoverdiv = '<div class="divMask" style="position: absolute; width: 1200px; height: 773px; left: 0px; top: 0px; background: #fff; opacity: 0; filter: alpha(opacity=0);z-index:1005;"></div>';
    $(obj).wrap('<div class="position:relative;"></div>');
    $(obj).before(hoverdiv);
    $(obj).data("mask",true);
}

function addAlert(content){
	var content = "<div style='color:black;'>"+content+"</div>";
	BootstrapDialog.show({
		closable:function(){
			$(this).on('click',function(){
				removeLoading();
				window.history.back(-1);
			});
		},
		title: '提示',
		message: content,
		buttons: [{
			icon: 'glyphicon glyphicon-check',
			label: '确定',
			cssClass: 'btn-primary',
			autospin: true,
			action: function () {
				window.history.back(-1);
			}
		}]
	});
}



//添加速度仪表盘
var gauge;
var myChart;
var widthChart;
var heightChart;
var xChart;
var yChart;
var minAngle;
var maxAngle;
var maxValue;
var dataRatio;
function addSpeedEchart(){
	gauge = document.getElementById('speedPanel');
	myChart = echarts.init(gauge);
	widthChart = getComputedStyle(gauge).width;
	heightChart = getComputedStyle(gauge).height;
	xChart = parseInt(widthChart.slice(0, -2), 0) / 2;
	yChart = parseInt(heightChart.slice(0, -2), 0) / 2;
	minAngle = -45;
	maxAngle = 225;
	maxValue = 350;
	dataRatio = maxValue / maxAngle;
    option = {
//		animation: false,   // 关掉动画, 否则拖动会有延迟
		tooltip : {
			formatter: "{a} <br/>{c} {b}"
		},
		series : [
			{
				name:'速度',
				type:'gauge',
				center: ['50%', '40%'], // 默认全局居中
				radius: 100,
				min:0,
				max:maxValue,
				splitNumber:7,
				startAngle: maxAngle,
				endAngle: minAngle,
				//仪表盘指针。
                pointer: {
                    show: true,
                    //指针长度
                    length:'100%',
                    width:5,
                },
                itemStyle:{//指针样式
		            normal:{
		                color:'#1e90ff'
		            }
		        },
				axisLine: {            // 坐标轴线
					lineStyle: {       // 属性lineStyle控制线条样式
						color: [[0.09, '#1e90ff'],[0.82, '#1e90ff'],[1, '#1e90ff']],
						width: 10,

					}
				},
				axisLabel: {            // 坐标轴小标记
					textStyle: {       // 属性lineStyle控制线条样式
						fontWeight: 'bolder',
						color: '#818181',
					}
				},
				axisTick: {            // 坐标轴小标记
					length :15,        // 属性length控制线长
					lineStyle: {       // 属性lineStyle控制线条样式
						color: 'auto',
					}
				},
				splitLine: {           // 分隔线
					length :25,         // 属性length控制线长
					lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
						width:3,
						color: '#1e90ff',
					}
				},
				title : {
					textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
						fontWeight: 'bolder',
						fontSize: 20,
						fontStyle: 'italic',
						color: '#3e3d3d',
					}
				},
//				detail : {
//					borderWidth: 1,
//					borderColor: '#ffff00',
//					offsetCenter: [0, '60%'],       // x, y，单位px
//					textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
//						fontWeight: 'bolder',
//						color: '#ffff00',
//						fontSize: 16
//					}
//				},
				detail : {
					borderWidth: 1,
					borderColor: '#2c2f33',
					offsetCenter: [0, '60%'],       // x, y，单位px
					textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
						fontWeight: 'bolder',
						color: '#2c2f33',
						fontSize: 16
					}
				},
				data:[{value: 40, name: 'km/h'}]
			}
		]
	};

    // 使用刚指定的配置项和数据显示图表。
    option.series[0].data[0].value = 0;
    $("#MANIputStorageId402").val(option.series[0].data[0].value);
	myChart.setOption(option);
	
	// 这里使用 zrender 的事件监听可以监听到画布的所有鼠标事件.    
//	myChart._zr.on('mousedown', function(event) {
//	    changeValue(event);
//	    myChart._zr.on('mousemove', changeValue);
//	});
//	myChart._zr.on('mouseup', function(event) {
//	    myChart._zr.off('mousemove', changeValue);
//	});
}

function changeValue(event) {
    var x2 = event.offsetX;
    var y2 = event.offsetY;
    // 当前点击位置的角度.
    var currentAngle = Math.atan2(yChart - y2, xChart - x2) * 180 / Math.PI;
    // 边界处理
    if (currentAngle < minAngle || currentAngle > maxAngle) {
        let _angle = Math.abs(currentAngle);
        if (_angle > 90) {
            currentAngle = maxAngle;
        } else {
            currentAngle = minAngle;
        }
    }
    // 转换回数据值, 这里就是实际的值, 默认保留2位小数.
    let value = (currentAngle * dataRatio).toFixed(0);
    option.series[0].data[0].value = value;
    myChart.setOption(option);
    $("#MANIputStorageId402").val(value);
}
//相位
function addXW(){
	$("#xwSlider").slider({
      orientation: "horizontal",
      range: "min",
      max: 1,
      value: 0,
      slide: xwRefreshSwatch,
    });
	var xwLocalStorage = localStorage.getItem('xwSlider');
	if(xwLocalStorage){
		 $("#xwSlider" ).slider( "value", Number(xwLocalStorage) );
	}
    sendTestSignal(3, 15, 2, "xwSlider", "");
	sendTestSignal(3, 16, 2, "xwSlider", "");
}
//相位切换时
function xwRefreshSwatch(){
	$("#xwSlider" ).slider( "value", Math.abs($( "#xwSlider" ).slider( "value" ) - 1));
	var a =6;
	if($( "#xwSlider" ).slider( "value" ) == 0){
		a=2;
	}
	sendTestSignal(3, 15, a, "xwSlider", "");
	sendTestSignal(3, 16, a, "xwSlider", "");
	localStorage.setItem('xwSlider', $( "#xwSlider" ).slider( "value" ));
}
//添加管压
//初始状态不发送请求，当有值改变时，并且鼠标抬起时才发送请求
var slderChangeBool = false;
function addPressure(){
	$("#perssureSlider0,#perssureSlider1,#perssureSlider2,#perssureSlider3,#perssureSlider4").slider({
      orientation: "vertical",
      range: "min",
      max: 1000,
      value: 127,
      slide: refreshSwatch,
      change: upSwatch
    });
    $("#perssureSlider0" ).slider( "value", 500 );
    $("#perssureSlider1" ).slider( "value", 0 );
    $("#perssureSlider2" ).slider( "value", 500 );
    $("#perssureSlider3" ).slider( "value", 500 );
    $("#perssureSlider4" ).slider( "value", 500 );
   
}
//slider鼠标抬起，发送请求
function upSwatch(event){
	if(slderChangeBool){
		var e1 = jQuery.Event('oninput');
		$("#"+event.target.id).parent().find("input:first").trigger(e1);
		slderChangeBool = false;
	}
}

//刷新slider的值
function refreshSwatch() {
	slderChangeBool = true;
	setPressureInput();
 }
//刷新管压中的输入框的值
function setPressureInput(){
	var perssureSlider0 = $( "#perssureSlider0" ).slider( "value" );
    var perssureSlider1 = $( "#perssureSlider1" ).slider( "value" );
    var perssureSlider2 = $( "#perssureSlider2" ).slider( "value" );
    var perssureSlider3 = $( "#perssureSlider3" ).slider( "value" );
    var perssureSlider4 = $( "#perssureSlider4" ).slider( "value" );
	$("#perssureSlider0").parent().find("input").val(perssureSlider0);
    $("#perssureSlider1").parent().find("input").val(perssureSlider1);
    $("#perssureSlider2").parent().find("input").val(perssureSlider2);
    $("#perssureSlider3").parent().find("input").val(perssureSlider3);
    $("#perssureSlider4").parent().find("input").val(perssureSlider4);
}

//添加数字软键盘
function addNumberKeyboard(){
	$(".numkeyboard").numkeyboard({
		keyboardRadix: 600, //键盘大小基数
		mainbackground: '#313439', //主背景色
		menubackground: '#313439', //头背景色
		exitbackground: '#4376A0', //关闭按钮背景色
		buttonbackground: 'transparent', //键盘背景色
		clickeve: true, //是否绑定元素click事件
	});
}
